package com.huangjue.backend.controller;

import com.huangjue.backend.entity.Demo;
import com.huangjue.backend.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.huangjue.backend.entity.StudentCourse;
import com.huangjue.backend.service.StudentCourseService;
import com.huangjue.backend.service.VideoFinishService;
import com.huangjue.backend.service.HomeworkFinishedService;
import com.huangjue.backend.service.VideoService;
import com.huangjue.backend.service.HomeworkService;
import com.huangjue.backend.entity.UserCertificate;
import com.huangjue.backend.entity.Certificate;
import com.huangjue.backend.mapper.UserCertificateMapper;
import com.huangjue.backend.mapper.CertificateMapper;
import org.springframework.beans.factory.annotation.Autowired;
import java.time.LocalDateTime;
import java.util.UUID;

@RestController
@RequestMapping("/demo")
@CrossOrigin(origins = "*")
public class DemoController {
    //11
    @Autowired
    private DemoService demoService;

    @Autowired
    private StudentCourseService studentCourseService;
    @Autowired
    private VideoFinishService videoFinishService;
    @Autowired
    private HomeworkFinishedService homeworkFinishedService;
    @Autowired
    private VideoService videoService;
    @Autowired
    private HomeworkService homeworkService;
    @Autowired
    private UserCertificateMapper userCertificateMapper;
    @Autowired
    private CertificateMapper certificateMapper;

    @PostMapping("/list")
    public ResponseEntity<Map<String, Object>> getDemos(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            Integer courseId = Integer.valueOf(request.get("courseId"));
            String token = request.get("token");
            // 简单token解析，格式：token_{userId}_xxxx
            Integer userId = null;
            if (token != null && token.startsWith("token_")) {
                String[] parts = token.split("_");
                if (parts.length >= 2) {
                    userId = Integer.valueOf(parts[1]);
                }
            }
            if (userId == null) {
                response.put("success", false);
                response.put("message", "token无效");
                return ResponseEntity.badRequest().body(response);
            }
            StudentCourse sc = studentCourseService.getByUserIdAndCourseId(userId, courseId);
            if (sc == null) {
                sc = new StudentCourse();
                sc.setDemoNum(0);
            }
            List<Demo> allDemos = demoService.getDemosByCourseId(courseId);
            //没demo，没选课不进入该选择
            if (allDemos.size()>0 && sc!=null){
            allDemos.sort((a, b) -> a.getDemoId() - b.getDemoId());
//            int openNum = sc.getDemoNum() != null ? sc.getDemoNum() : 0;
            int openNum = sc.getDemoNum();
            System.out.println("openNum=" + openNum + ", allDemos.size()=" + allDemos.size());
            List<Object> result = new java.util.ArrayList<>();
            int count=0;
            for (int i = 0; i < allDemos.size(); i++) {
                Demo demo = allDemos.get(i);
                boolean isOpen = i < openNum;
                boolean isFinished = false;
                if (isOpen) {
                    // 检查该demo下所有视频和作业是否完成
                    List<com.huangjue.backend.entity.Video> videos = videoService.getVideosByDemoId(demo.getDemoId());
                    boolean allVideosWatched = true;
                    for (com.huangjue.backend.entity.Video video : videos) {
                        if (!videoFinishService.isVideoWatched(userId, demo.getDemoId(), video.getVideoId())) {
                            allVideosWatched = false;
                            break;
                        }
                    }
                    List<com.huangjue.backend.entity.Homework> homeworks = homeworkService.getHomeworksByDemoId(demo.getDemoId());
                    boolean allHomeworksFinished = true;
                    for (com.huangjue.backend.entity.Homework homework : homeworks) {
                        if (homeworkFinishedService.selectByUserIdAndHomeworkId(userId, homework.getHomeworkId()) == null) {
                            allHomeworksFinished = false;
                            break;
                        }
                    }
                    isFinished = allVideosWatched && allHomeworksFinished;

                }
                //计算已完成demo数量
                if (isFinished){count++;}
//                这里默认发布之后不会再进行视频更新了
                if (i<=count) {
                Map<String, Object> map = new HashMap<>();
                map.put("demoId", demo.getDemoId());
                map.put("demoTitle", demo.getDemoTitle());
                
                // 添加调试日志
                System.out.println("Demo ID: " + demo.getDemoId());
                System.out.println("Demo Title: " + demo.getDemoTitle());
                    map.put("courseId", demo.getCourseId());
                    map.put("description", demo.getDescription());
                    map.put("isPublished", demo.getIsPublished());
                    map.put("isOpen", true);
                    map.put("isFinished", isFinished);
                    result.add(map);
                } else {
                    Map<String, Object> map = new HashMap<>();
                    map.put("demoTitle", demo.getDemoTitle());
                    map.put("courseId", demo.getCourseId());
                    map.put("description", demo.getDescription());
                    map.put("isPublished", demo.getIsPublished());
                    map.put("isOpen", false);
                    map.put("isFinished", false);
                    result.add(map);
                }
            }
            //确定开放课程数量
            openNum=allDemos.size()>count?count+1: allDemos.size();

//            修改了学生已学习课程的进度，为个人中心调接口提供方便
            Integer isChange= demoService.updateOpenNum(openNum,userId,courseId);
//            System.out.println(isChange);
            
            // 检查课程是否完成
            boolean isCourseFinished = false;
            if (sc != null && sc.getDemoUnlock() != null && openNum >= sc.getDemoUnlock()) {
                isCourseFinished = true;
                // 更新course_study表的is_finished字段为1
                demoService.updateCourseFinished(userId, courseId);
                // 检查是否已存在证书记录
                UserCertificate existingCert = userCertificateMapper.selectByUserIdAndCourseId(Long.valueOf(userId), courseId);
                if (existingCert == null) {
                    // 生成证书记录
                    Certificate cert = certificateMapper.selectEnabled();
                    if (cert != null) {
                        UserCertificate userCert = new UserCertificate();
                        userCert.setCertificateId(cert.getId());
                        userCert.setUserId(Long.valueOf(userId));
                        userCert.setCourseId(courseId);
                        userCert.setIssueDate(LocalDateTime.now());
                        userCert.setCreateTime(LocalDateTime.now());
                        userCert.setIsValid(1);
                        // 生成16位数字证书编号
                        String certNo = String.format("%016d", System.currentTimeMillis() % 10000000000000000L);
                        userCert.setCertNo(certNo);
                        userCertificateMapper.insert(userCert);
                    }
                }
            }
            
            if (isChange==1){
            response.put("success", true);
            response.put("message", "获取Demo列表成功");
            response.put("data", result);
            response.put("openNum", openNum);
            response.put("isCourseFinished", isCourseFinished);
            }else{
                System.out.println("更新student_course表失败");
            }
            }
            return ResponseEntity.ok()
                .contentType(org.springframework.http.MediaType.APPLICATION_JSON)
                .header("Content-Type", "application/json;charset=UTF-8")
                .body(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取Demo列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError()
                .contentType(org.springframework.http.MediaType.APPLICATION_JSON)
                .header("Content-Type", "application/json;charset=UTF-8")
                .body(response);
        }
    }

    @PostMapping("/choose")
    public ResponseEntity<Map<String, Object>> chooseCourse(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            Integer courseId = Integer.valueOf(request.get("courseId"));
            String token = request.get("token");
            // 简单token解析，格式：token_{userId}_xxxx
            Integer userId = null;
            if (token != null && token.startsWith("token_")) {
                String[] parts = token.split("_");
                if (parts.length >= 2) {
                    userId = Integer.valueOf(parts[1]);
                }
            }
            if (userId == null) {
                response.put("success", false);
                response.put("message", "token无效");
                return ResponseEntity.badRequest().body(response);
            }
            //这个需要后台进行更新操作,获取到总共多少demo
            int DemosNum = demoService.getDemosNum(courseId);

            StudentCourse sc = new StudentCourse();
            sc.setUserId(userId);
            sc.setCourseId(courseId);
            sc.setDemoNum(1);
            sc.setDemoUnlock(DemosNum);
            //增加一个逻辑，只要后台修改了demo的数量，这边就需要更改总数，在后台需要加上这个逻辑
            if (studentCourseService.save(sc) != 1) {
                response.put("success", false);
                response.put("message", "获取Demo列表失败");
                return ResponseEntity.badRequest().body(response);
            }
            response.put("success", true);
            response.put("message", "选课成功");
            return ResponseEntity.ok()
                .contentType(org.springframework.http.MediaType.APPLICATION_JSON)
                .header("Content-Type", "application/json;charset=UTF-8")
                .body(response);
        } catch (Exception e) {
            response.put("success", false);
//            response.put("message", "获取Demo列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError()
                .contentType(org.springframework.http.MediaType.APPLICATION_JSON)
                .header("Content-Type", "application/json;charset=UTF-8")
                .body(response);
        }
    }

    /**
     * 根据demoId获取courseId
     */
    @GetMapping("/courseId/{demoId}")
    public ResponseEntity<Map<String, Object>> getCourseIdByDemoId(@PathVariable Integer demoId) {
        Map<String, Object> response = new HashMap<>();
        try {
            Integer courseId = demoService.getCourseIdByDemoId(demoId);
            response.put("success", true);
            response.put("data", courseId);
            response.put("message", "获取课程ID成功");
            return ResponseEntity.ok()
                .contentType(org.springframework.http.MediaType.APPLICATION_JSON)
                .header("Content-Type", "application/json;charset=UTF-8")
                .body(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取课程ID失败: " + e.getMessage());
            return ResponseEntity.internalServerError()
                .contentType(org.springframework.http.MediaType.APPLICATION_JSON)
                .header("Content-Type", "application/json;charset=UTF-8")
                .body(response);
        }
    }
    
    /**
     * 测试编码的端点
     */
    @GetMapping("/test-encoding")
    public ResponseEntity<Map<String, Object>> testEncoding() {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "测试中文编码：获取Demo列表成功");
        response.put("data", "这是一个测试数据，包含中文内容");
        return ResponseEntity.ok()
            .contentType(org.springframework.http.MediaType.APPLICATION_JSON)
            .header("Content-Type", "application/json;charset=UTF-8")
            .body(response);
    }
}
